package yue.shen.android.demo.activity

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import yue.shen.android.demo.R

class Demo1Adapter(private val list: MutableList<Demo1Data>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    fun updateData(list: MutableList<Demo1Data>) {
        this.list.clear()
        this.list.addAll(list)
        notifyDataSetChanged()
    }

    fun addData(list: MutableList<Demo1Data>) {
        this.list.addAll(list)
        notifyDataSetChanged()
    }

    fun addFooter() {
        this.list.add(Demo1Data(1, ""))
        notifyDataSetChanged()
    }

    fun getData() = this.list

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        return if (viewType == 0) {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_demo1_style1, null)
            Demo1Style1Item(view)
        } else {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_demo1_style2, null)
            Demo1Style2Item(view)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is Demo1Style1Item -> {
                holder.bindData(list[position].text, position)
            }
            is Demo1Style2Item -> {
                val layoutParams = holder.itemView.layoutParams
                if (layoutParams != null && layoutParams is StaggeredGridLayoutManager.LayoutParams) {
                    layoutParams.isFullSpan = true
                } else {
                    val newLayoutParams = StaggeredGridLayoutManager.LayoutParams(
                        StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT,
                        StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT
                    )
                    newLayoutParams.isFullSpan = true
                    holder.itemView.layoutParams = newLayoutParams
                }

                holder.bindData(list[position].text)
            }
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun getItemViewType(position: Int): Int {
        return list[position].type
    }

    override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
        super.onViewAttachedToWindow(holder)
    }

}
